﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Aribaccio.Office.Demo
{
    public class OfficerDataTableBatch
    {
        protected PeriodicTaskManual MonitorTask { get; set; }
        protected ConcurrentQueue<string[]> DataRows { get; set; }

        public DataTable DataTableBatch { get; protected set; }
        public bool HasDataRows => DataRows != null && DataRows.Count > 0;

        public OfficerDataTableBatch(DataTable dataTable)
        {
            this.DataTableBatch = dataTable;
            this.DataRows = new ConcurrentQueue<string[]>();
            this.MonitorTask = new PeriodicTaskManual($"批次导出文件服务", 0, MonitorTaskAction, true, true);
        }

        public Task AddData(string rowLine)
        {
            return Task.Run(() =>
            {
                var dataValues = rowLine?.Split(new char[] { ',' });
                if (dataValues == null || dataValues.Length <= 0) return;
                DataRows.Enqueue(dataValues);
            });
        }

        public Task AddData(string[] rows)
        {
            return Task.Run(() =>
            {
                DataRows.Enqueue(rows);
            });
        }

        protected void MonitorTaskAction()
        {
            if (DataRows == null || DataRows.Count <= 0) return;
            while (DataRows.TryDequeue(out var rowData) && rowData != null)
            {
                DataTableBatch.Rows.Add(rowData);
            }
        }
    }
}
